<template>
  <div class="d-flex">
    <div class="d-flex flex-column flex-grow-1">
      <v-card class="mb-3 pa-3 position-sticky" style="top: 10px">
        <div class="d-flex justify-space-between" style="height: 40px">
          <v-text-field
            v-model="searchQuery"
            class="flex-grow-1"
            clearable
            :label="t('passMain.searchPlaceholder')"
            :prepend-inner-icon="mdiMagnify"
            variant="outlined"
          />
          <div class="d-flex align-center ml-2">
            <v-btn
              color="primary"
              :icon="mdiPlus"
              rounded="lg"
              @click="showAddDialog = true"
            ></v-btn>
          </div>
        </div>
      </v-card>
      <v-card class="flex-grow-1 d-flex flex-column" flat>
        <v-card-text class="pa-4 flex-grow-1 d-flex flex-column">
          <!-- 密码列表容器 -->
          <div class="flex-grow-1 overflow-y-auto password-list-container">
            <!-- 密码列表内容 -->
            <div>
              <!-- 空状态 -->
              <div v-if="filteredCredentials.length === 0" class="text-center py-8">
                <v-icon class="mb-4" color="grey-lighten-1" :icon="mdiLock" size="64" />
                <div class="text-h6 text-medium-emphasis">
                  {{ searchQuery ? t('passMain.empty.noMatch') : t('passMain.empty.none') }}
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  {{ searchQuery ? t('passMain.empty.tryOther') : t('passMain.empty.startSaving') }}
                </div>
              </div>

              <!-- 密码列表 -->
              <v-virtual-scroll v-else item-key="_id" :items="filteredCredentials">
                <template #default="{ item }">
                  <v-list-item
                    :key="item._id"
                    class="credential-item mb-2"
                    rounded="lg"
                    variant="tonal"
                  >
                    <template #prepend>
                      <v-avatar class="mr-3" size="40">
                        <v-img
                          v-if="item.favicon_url"
                          :alt="item.domain"
                          :src="item.favicon_url"
                          @error=""
                        />
                        <v-icon v-else :icon="mdiWeb" />
                      </v-avatar>
                    </template>

                    <v-list-item-title class="font-weight-medium">
                      {{ item.site_name || item.domain }}
                    </v-list-item-title>

                    <v-list-item-subtitle class="d-flex align-center">
                      <span>{{ item.username }}</span>
                      <v-chip
                        v-if="!item.auto_fill_enabled"
                        class="ml-2"
                        color="warning"
                        size="x-small"
                      >
                        {{ t('passMain.autoFillDisabled') }}
                      </v-chip>
                    </v-list-item-subtitle>

                    <template #append>
                      <div class="d-flex align-center">
                        <v-btn
                          v-tooltip:start="
                            item.server_id ? t('passMain.sync.synced') : t('passMain.sync.unsynced')
                          "
                          :color="item.server_id ? 'success' : 'grey'"
                          :icon="item.server_id ? mdiCloudLock : mdiCloudOff"
                          size="small"
                          variant="text"
                          @click=""
                        />
                        <!-- 复制用户名 -->
                        <!--                        <v-btn
                          :icon="mdiContentCopy"
                          size="small"
                          variant="text"
                          @click="
                            copyToClipboard(item.username, t('passMain.messages.usernameCopied'))
                          "
                        />-->

                        <!-- 复制密码 -->
                        <!--                        <v-btn
                          :icon="mdiKey"
                          size="small"
                          variant="text"
                          @click="copyPassword(item)"
                        />-->

                        <!-- 编辑 -->
                        <v-btn
                          :icon="mdiPencil"
                          size="small"
                          variant="text"
                          @click="editCredential(item)"
                        />

                        <!-- 删除 -->
                        <v-btn
                          color="error"
                          :icon="mdiDelete"
                          size="small"
                          variant="text"
                          @click="deleteCredential(item)"
                        />
                      </div>
                    </template>
                  </v-list-item>
                </template>
              </v-virtual-scroll>
              <!--              <v-list v-else class="pa-0">
                              <v-list-item
                                v-for="credential in filteredCredentials"
                                :key="credential._id"
                                class="credential-item mb-2"
                                rounded="lg"
                                variant="tonal"
                              >
                                <template #prepend>
                                  <v-avatar class="mr-3" size="40">
                                    <v-img
                                      v-if="credential.favicon_url"
                                      :alt="credential.domain"
                                      :src="credential.favicon_url"
                                      @error="credential.favicon_url = ''"
                                    />
                                    <v-icon v-else :icon="mdiWeb" />
                                  </v-avatar>
                                </template>

                                <v-list-item-title class="font-weight-medium">
                                  {{ credential.site_name || credential.domain }}
                                </v-list-item-title>

                                <v-list-item-subtitle class="d-flex align-center">
                                  <span>{{ credential.username }}</span>
                                  <v-chip
                                    v-if="!credential.auto_fill_enabled"
                                    class="ml-2"
                                    color="warning"
                                    size="x-small"
                                  >
                                    {{ t('passMain.autoFillDisabled') }}
                                  </v-chip>
                                </v-list-item-subtitle>

                                <template #append>
                                  <div class="d-flex align-center">
                                    <v-btn
                                      v-tooltip:start="
                                        credential.server_id
                                          ? t('passMain.sync.synced')
                                          : t('passMain.sync.unsynced')
                                      "
                                      :color="credential.server_id ? 'success' : 'grey'"
                                      :icon="credential.server_id ? mdiCloudLock : mdiCloudOff"
                                      size="small"
                                      variant="text"
                                      @click=""
                                    />
                                    &lt;!&ndash; 复制用户名 &ndash;&gt;
                                    <v-btn
                                      :icon="mdiContentCopy"
                                      size="small"
                                      variant="text"
                                      @click="
                                        copyToClipboard(
                                          credential.username,
                                          t('passMain.messages.usernameCopied')
                                        )
                                      "
                                    />

                                    &lt;!&ndash; 复制密码 &ndash;&gt;
                                    <v-btn
                                      :icon="mdiKey"
                                      size="small"
                                      variant="text"
                                      @click="copyPassword(credential)"
                                    />

                                    &lt;!&ndash; 编辑 &ndash;&gt;
                                    <v-btn
                                      :icon="mdiPencil"
                                      size="small"
                                      variant="text"
                                      @click="editCredential(credential)"
                                    />

                                    &lt;!&ndash; 删除 &ndash;&gt;
                                    <v-btn
                                      color="error"
                                      :icon="mdiDelete"
                                      size="small"
                                      variant="text"
                                      @click="deleteCredential(credential)"
                                    />
                                  </div>
                                </template>
                              </v-list-item>
                            </v-list>-->
            </div>
          </div>
        </v-card-text>
      </v-card>
    </div>

    <v-card class="ml-3 position-sticky" style="max-height: 300px; top: 10px">
      <v-card-title class="text-h6 d-flex align-center">
        <v-icon class="mr-2" :icon="mdiCog" />
        {{ t('passMain.settings.title') }}
      </v-card-title>

      <v-card-text>
        <v-switch
          v-model="localSettings.state.enabled"
          class="mb-3"
          color="primary"
          density="compact"
          hide-details
          :label="t('passMain.settings.enableManager')"
          @update:model-value="updateSetting('enabled', $event)"
        />

        <v-switch
          v-model="localSettings.state.auto_fill_enabled"
          class="mb-3"
          color="primary"
          density="compact"
          :disabled="!localSettings.state.enabled"
          hide-details
          :label="t('passMain.settings.enableAutoFill')"
          @update:model-value="updateSetting('auto_fill_enabled', $event)"
        />

        <v-switch
          v-model="localSettings.state.save_prompt_enabled"
          class="mb-3"
          color="primary"
          density="compact"
          :disabled="!localSettings.state.enabled"
          hide-details
          :label="t('passMain.settings.enableSavePrompt')"
          @update:model-value="updateSetting('save_prompt_enabled', $event)"
        />

        <v-switch
          v-model="localSettings.state.sync_enabled"
          class="mb-3"
          color="primary"
          density="compact"
          :disabled="!localSettings.state.enabled"
          hide-details
          :label="t('passMain.settings.enableCloudSync')"
          @update:model-value="updateSetting('sync_enabled', $event)"
        />

        <v-btn
          v-if="
            localSettings.state.sync_enabled &&
            syncedCount !== passwordManagerStore.credentials.length
          "
          block
          color="primary"
          :disabled="!localSettings.state.enabled || isSyncing"
          :loading="isSyncing"
          variant="outlined"
          @click="handleSync"
        >
          {{ t('passMain.settings.syncNow') }}
        </v-btn>
      </v-card-text>
    </v-card>
    <!-- 消息提示 -->
    <v-snackbar v-model="showMessage" :color="messageType" location="top" :timeout="3000">
      {{ message }}
    </v-snackbar>

    <!-- 添加/编辑密码对话框 -->
    <PasswordEditDialog
      v-model="showAddDialog"
      :credential="editingCredential"
      @saved="handleCredentialSaved"
    />
    <!-- 删除确认对话框 -->
    <v-dialog v-model="showDeleteDialog" max-width="400">
      <v-card>
        <v-card-title class="text-error">
          <v-icon class="mr-2" :icon="mdiAlertCircle" />
          {{ t('passMain.deleteDialog.title') }}
        </v-card-title>

        <v-card-text>
          {{ t('passMain.deleteDialog.confirm1') }}
          <strong>{{ deletingCredential?.domain }}</strong>
          {{ t('passMain.deleteDialog.confirm2') }}
          {{ t('passMain.deleteDialog.cannotUndo') }}
        </v-card-text>

        <v-card-actions>
          <v-spacer />
          <v-btn @click="showDeleteDialog = false">{{ t('passMain.actions.cancel') }}</v-btn>
          <v-btn color="error" :loading="isDeleting" @click="confirmDelete"
            >{{ t('passMain.actions.delete') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import {
  mdiAlertCircle,
  mdiCloudLock,
  mdiCloudOff,
  mdiCog,
  mdiDelete,
  mdiLock,
  mdiMagnify,
  mdiPencil,
  mdiPlus,
  mdiWeb
} from '@mdi/js'
import { usePasswordManagerStore } from '@/stores/passwordManager'
import PasswordEditDialog from './PasswordEditDialog.vue'
import userApi from '@/ajax/user'
import { createStorageState } from 'global-state'

import { useI18n } from 'vue-i18n'

// 类型定义
interface DecryptedUserCredential {
  _id: string
  id?: number
  domain: string
  site_name?: string | null
  username: string
  password: string
  favicon_url?: string | null
  auto_fill_enabled: boolean
  is_synced: boolean
  server_id?: string | null
  last_used_at?: Date | null
  created_at: Date
  updated_at: Date
}

const { t } = useI18n()

// 响应式数据
const passwordManagerStore = usePasswordManagerStore()
const searchQuery = ref('')
const showAddDialog = ref(false)
const showDeleteDialog = ref(false)
const isDeleting = ref(false)
const editingCredential = ref<DecryptedUserCredential | null>(null)
const deletingCredential = ref<DecryptedUserCredential | null>(null)

// 消息提示
const showMessage = ref(false)
const message = ref('')
const messageType = ref<'success' | 'error' | 'warning' | 'info'>('info')

// 同步状态
const isSyncing = ref(false)

// 本地设置副本
const localSettings = createStorageState(
  'passwordManagerSettings',
  {
    enabled: true,
    auto_fill_enabled: true,
    save_prompt_enabled: true,
    sync_enabled: true
  },
  1
)

// 计算属性
const filteredCredentials = computed(() => {
  if (!searchQuery.value) {
    return passwordManagerStore.credentials
  }
  const query = searchQuery.value.toLowerCase()
  return passwordManagerStore.credentials.filter(
    credential =>
      credential.domain.toLowerCase().includes(query) ||
      credential.site_name?.toLowerCase().includes(query) ||
      credential.username.toLowerCase().includes(query)
  )
})

const syncedCount = computed(() => {
  return passwordManagerStore.credentials.filter(cred => cred.is_synced).length
})

/**
 * 复制到剪贴板
 */
async function copyToClipboard(text: string, successMessage: string): Promise<void> {
  try {
    await navigator.clipboard.writeText(text)
    showMessageToUser(successMessage, 'success')
  } catch (error) {
    console.error('复制失败:', error)
    showMessageToUser(t('passMain.messages.copyFailed'), 'error')
  }
}

/**
 * 复制密码
 */
async function copyPassword(credential: DecryptedUserCredential): Promise<void> {
  await copyToClipboard(credential.password, t('passMain.messages.passwordCopied'))

  // 更新最后使用时间
  try {
    await passwordManagerStore.updateLastUsed(credential._id)
  } catch (error) {
    console.error('更新最后使用时间失败:', error)
  }
}

/**
 * 编辑凭据
 */
function editCredential(credential: DecryptedUserCredential): void {
  editingCredential.value = credential
  showAddDialog.value = true
}

/**
 * 删除凭据
 */
async function deleteCredential(credential: DecryptedUserCredential): Promise<void> {
  showDeleteDialog.value = true
  deletingCredential.value = credential
}

/**
 * 确认删除
 */
async function confirmDelete(): Promise<void> {
  if (!deletingCredential.value) return

  isDeleting.value = true
  console.log(deletingCredential.value)
  try {
    const success = await passwordManagerStore.deleteCredential(deletingCredential.value._id)
    if (success) {
      // 删除云端
      if (deletingCredential.value.server_id) {
        await userApi.passUpdate({ delete_ids: [Number(deletingCredential.value.server_id)] })
      }
      showMessageToUser(t('passMain.messages.deleted'), 'success')
      showDeleteDialog.value = false
    } else {
      showMessageToUser(t('passMain.messages.deleteFailed'), 'error')
    }
  } catch (error) {
    console.error('删除失败:', error)
    showMessageToUser(t('passMain.messages.deleteFailed'), 'error')
  } finally {
    isDeleting.value = false
    deletingCredential.value = null
  }
}

/**
 * 处理凭据保存
 */
function handleCredentialSaved(): void {
  console.log('处理凭据保存', editingCredential.value)
  showAddDialog.value = false
  editingCredential.value = null
  passwordManagerStore.loadCredentials()
  if (localSettings.state.sync_enabled) {
    handleSync()
  }
}

/**
 * 更新设置
 */
function updateSetting(key: string, value: any): void {
  const new_settings = { ...localSettings.state, [key]: value }
  localSettings.set(new_settings)
  showMessageToUser(t('passMain.messages.settingsSaved'), 'success')
}

/**
 * 显示消息
 */
function showMessageToUser(msg: string, type: 'success' | 'error' | 'warning' | 'info'): void {
  message.value = msg
  messageType.value = type
  showMessage.value = true
}

/**
 * 处理云端同步
 */
async function handleSync(): Promise<void> {
  if (!localSettings.state.sync_enabled) {
    showMessageToUser(t('passMain.messages.enableCloudSyncFirst'), 'warning')
    return
  }

  isSyncing.value = true
  try {
    // 1. 先从云端拉取数据
    const cloudCredentials = await userApi.passList()
    console.log('从云端获取到凭据:', cloudCredentials.length)
    let imported = 0,
      updated = 0
    if (cloudCredentials.length > 0) {
      const syncFromResult = await passwordManagerStore.syncFromCloud(cloudCredentials)
      if (syncFromResult.success) {
        imported = syncFromResult.imported || 0
        updated = syncFromResult.updated || 0
        console.log(
          `从云端同步成功: ${syncFromResult.imported} 新增, ${syncFromResult.updated} 更新`
        )
      } else {
        console.error('从云端同步失败:', syncFromResult.error)
      }
    }

    // 2. 再将本地未同步的数据推送到云端
    const syncToResult = await passwordManagerStore.syncToCloud()
    if (syncToResult.success) {
      console.log(`同步到云端成功: ${syncToResult.synced} 成功, ${syncToResult.failed} 失败`)

      // 重新加载凭据以更新UI
      await passwordManagerStore.loadCredentials()

      showMessageToUser(
        t('passMain.sync.completed', {
          imported,
          updated,
          uploaded: syncToResult.synced || 0
        }),
        'success'
      )
    } else {
      showMessageToUser(syncToResult.error || t('passMain.sync.failed'), 'error')
    }
  } catch (error) {
    console.error('同步失败:', error)
    const reason = error instanceof Error ? error.message : t('passMain.common.unknownError')
    showMessageToUser(t('passMain.sync.failedWithReason', { reason }), 'error')
  } finally {
    isSyncing.value = false
  }
}

// 组件挂载时初始化
onMounted(async () => {
  await passwordManagerStore.initialize()
  console.log('搜索:', passwordManagerStore.credentials)
})
</script>

<style scoped>
.credential-item {
  transition: all 0.2s ease;
}

.credential-item:hover {
  background-color: rgba(var(--v-theme-primary), 0.04);
}

.overflow-y-auto {
  overflow-y: auto;
}

/* 密码列表容器 */
.password-list-container {
  position: relative;
}
</style>
<i18n>
{
  "zhHans": {
    "passMain": {
      "actions": {
        "delete": "删除",
        "cancel": "取消"
      },
      "searchPlaceholder": "搜索网站或用户名",
      "empty": {
        "noMatch": "未找到匹配的密码",
        "none": "暂无保存的密码",
        "tryOther": "尝试使用其他关键词搜索",
        "startSaving": "开始保存您的登录信息"
      },
      "autoFillDisabled": "自动填充已禁用",
      "sync": {
        "synced": "已同步",
        "unsynced": "未同步",
        "completed": "同步完成: {imported} 新增, {updated} 更新, {uploaded} 上传",
        "failed": "同步失败",
        "failedWithReason": "同步失败: {reason}"
      },
      "deleteDialog": {
        "title": "确认删除",
        "confirm1": "确定要删除",
        "confirm2": "的登录信息吗？",
        "cannotUndo": "此操作无法撤销。"
      },
      "settings": {
        "title": "功能设置",
        "enableManager": "启用密码管理器",
        "enableAutoFill": "启用自动填充",
        "enableSavePrompt": "显示保存密码提示",
        "enableCloudSync": "启用云端同步",
        "syncNow": "立即同步"
      },
      "messages": {
        "usernameCopied": "用户名已复制到剪贴板",
        "passwordCopied": "密码已复制到剪贴板",
        "copyFailed": "复制失败",
        "deleted": "密码已删除",
        "deleteFailed": "删除失败",
        "settingsSaved": "设置已保存",
        "enableCloudSyncFirst": "请先启用云端同步"
      },
      "common": {
        "unknownError": "未知错误"
      }
    }
  },
  "en": {
    "passMain": {
      "actions": {
        "delete": "Delete",
        "cancel": "Cancel"
      },
      "searchPlaceholder": "Search website or username",
      "empty": {
        "noMatch": "No matching passwords found",
        "none": "No saved passwords",
        "tryOther": "Try searching with other keywords",
        "startSaving": "Start saving your login information"
      },
      "autoFillDisabled": "Auto-fill disabled",
      "sync": {
        "synced": "Synced",
        "unsynced": "Not synced",
        "completed": "Sync completed: {imported} added, {updated} updated, {uploaded} uploaded",
        "failed": "Sync failed",
        "failedWithReason": "Sync failed: {reason}"
      },
      "deleteDialog": {
        "title": "Confirm Delete",
        "confirm1": "Are you sure you want to delete login information for",
        "confirm2": "?",
        "cannotUndo": "This action cannot be undone."
      },
      "settings": {
        "title": "Settings",
        "enableManager": "Enable password manager",
        "enableAutoFill": "Enable auto-fill",
        "enableSavePrompt": "Show save password prompt",
        "enableCloudSync": "Enable cloud sync",
        "syncNow": "Sync now"
      },
      "messages": {
        "usernameCopied": "Username copied to clipboard",
        "passwordCopied": "Password copied to clipboard",
        "copyFailed": "Copy failed",
        "deleted": "Password deleted",
        "deleteFailed": "Delete failed",
        "settingsSaved": "Settings saved",
        "enableCloudSyncFirst": "Please enable cloud sync first"
      },
      "common": {
        "unknownError": "Unknown error"
      }
    }
  }
}

</i18n>
